package com.ruoyi.common.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ruoyi.common.exception.ServiceException;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class BigModelWeb  {
    // 地址与鉴权信息  https://spark-api.xf-yun.com/v1.1/chat   1.5地址  domain参数为general
    // 地址与鉴权信息  https://spark-api.xf-yun.com/v2.1/chat   2.0地址  domain参数为generalv2
    //https://spark-api.xf-yun.com/v3.5/chat
    //ws(s)://spark-api.xf-yun.com/v3.5/chat
    public static final String hostUrl = "https://spark-api-open.xf-yun.com/v1/chat/completions";//"https://spark-api.xf-yun.com/v2.1/chat";
    public static final String appid = "f5b4028b";//"56369def";
    public static final String apiSecret = "NjA5NzVlY2U1NDBjYjZlZDBhNWQ1YjZl";//"ZDVmZjIwOWJlMWZiYmVhODNkMmUzYjQz";
    public static final String apiKey = "a78a5ef84cada44280c962784134b8b9";//"5aee275a83ac59d9d354823e89e0bb00";

    // 个性化参数
    private String userId;
    private Boolean wsCloseFlag;

    private static Boolean totalFlag=true; // 控制提示用户是否输入
    // 构造函数
    public BigModelWeb(String userId, Boolean wsCloseFlag) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
    }

    public static String chat(String content) throws Exception {
        String result = "";
        //试3次 结束
        try{
            result = BigModelWeb.chat2(content);
        }catch (Exception ex){
            try{
                result = BigModelWeb.chat2(content);
            }catch (Exception ex2){
                try{
                    result = BigModelWeb.chat2(content);
                }catch (Exception ex3){
                    throw new ServiceException("BigModelWeb net error");
                }
            }
        }
        return result;
    }

    // 主函数
    public static String chat2(String content) throws Exception {
        // 个性化参数入口，如果是并发使用，可以在这里模拟
        /*
        选择请求的模型版本
        general指向Lite版本；
        generalv3指向Pro版本；
        pro-128k指向Pro-128K版本；
        generalv3.5指向Max版本；
        4.0Ultra指向4.0 Ultra版本；
        */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", "generalv3.5");//generalv3.5   general   pro-128k
        jsonObject.put("temperature", 0.01);

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonMsgObject = new JSONObject();
        jsonMsgObject.put("role", "user");
        jsonMsgObject.put("content", content);
        jsonMsgObject.put("max_tokens", 8192);

        jsonArray.add(jsonMsgObject);

        jsonObject.put("messages", jsonArray);

        String json = jsonObject.toJSONString();
        System.out.println("======json========" + json);

        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer "+apiKey+":"+apiSecret);
        connection.setConnectTimeout(60000);//连接超时60000
        connection.setReadTimeout(60000);//读取超时
        connection.setDoOutput(true);

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(json.getBytes());
        outputStream.flush();

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }

        connection.disconnect();

        jsonObject = JSONObject.parseObject(response.toString());
        jsonArray = jsonObject.getJSONArray("choices");
        JSONObject jsonArr01 = (JSONObject)jsonArray.get(0);
        JSONObject jsonMessage = jsonArr01.getJSONObject("message");


        return jsonMessage.getString("content").toString().replace("\n", "").replace("`json", "").replace("`", "");
    }


}
